
from . import api
from ihome.utils.commons import login_required
from flask import g, current_app, jsonify, request, session
from ihome.utils.response_code import RET
from ihome.models import User, IntegralGoods, GoodsOrder, GoodsSort
from ihome import db, constants
import os


@api.route("/goods/all", methods=["GET"])
def get_goods():
    """所有的商品信息
        可能存在筛选等等
        筛选的方式：按积分区间、按分类(需要前端先查询分类接口)、按销售量、积分价格从高的到低
        搜说框的筛选：按标题
    """
    sort_key = request.args.get("sort_key", "new")  # 排序关键字
    page = request.args.get("p")  # 页数
    vague = request.args.get("v")  # 模糊查询 按标题

    # 筛选条件
    # --积分区间
    integral_high = request.args.get("integral_high")  # 最高积分
    integral_low = request.args.get("integral_low")  # 最低积分
    check_good_s = request.args.get("check_good_s")  # 按用户选择的分类

    # 处理页数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 过滤条件的参数列表容器
    filter_params = []
    filter_params_two = []
    # 填充过滤参数
    # 时间条件
    # conflict_orders = None
    # 积分区间
    if integral_high and integral_low is not None:
        filter_params.append(IntegralGoods.need_integral.between(integral_low,integral_high ))
    # 商品分类
    if check_good_s:
        filter_params_two.append(IntegralGoods.sort_id == check_good_s)

    integral_query = IntegralGoods.query
    # 单关键字 多条件查询

    if vague:
        integral_query = integral_query.filter(
            IntegralGoods.name.ilike("%" + vague + "%"))

    # 查询数据库
    # 排序条件
    if sort_key == "2":
        integral_query = integral_query.filter(*filter_params).filter(*filter_params_two) \
            .order_by(IntegralGoods.need_integral.asc())
    elif sort_key == "3":
        integral_query = integral_query.filter(*filter_params).filter(*filter_params_two) \
            .order_by(IntegralGoods.need_integral.desc())
    else:  # 新旧
        integral_query = integral_query.filter(*filter_params).filter(*filter_params_two) \
            .order_by(IntegralGoods.volume.desc())

    # 处理分页paginate()函数为处理分页的函数
    try:
        #                               当前页数          每页数据量                              自动的错误输出
        page_obj = integral_query.paginate(page=page, per_page=constants.HOUSE_LIST_PAGE_CAPACITY, error_out=False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    # 获取页面数据
    goods_li = page_obj.items
    goods = []
    for goods_index in goods_li:
        goods.append(goods_index.to_base_dict())

    # 获取总页数
    total_page = page_obj.pages

    return jsonify(errno=RET.OK, errmsg="OK", data={"total_page": total_page, "goods": goods, "current_page": page})


@api.route("/goods/get_sort", methods=["GET"])
def get_good_sort():
    """获取商品分类"""
    try:
        sort_info = GoodsSort.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取设备信息")
    sort_list = []
    if sort_info:
        for sort in sort_info:
            sort_list.append(sort.to_dict())

    return jsonify(errno=RET.OK, errmsg="获取成功", data=sort_list)


@api.route("/goods/get_goods_del/<int:goods_id>", methods=["GET"])
def get_good_del(goods_id):
    """获取商品详情"""
    # user_id = session.get("user_id", "-1")
    # 校验参数
    if not goods_id:
        return jsonify(errno=RET.PARAMERR, errmsg="参数缺失")

    # 先从redis缓存中获取信息
    # try:
    #     ret = redis_store.get("house_info_%s" % house_id)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     ret = None
    # if ret:
    #     current_app.logger.info("hit house info redis")
    #     return ret, 200, {"Content-Type": "application/json"}

    # 查询数据库
    try:
        goods = IntegralGoods.query.get(goods_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not goods:
        return jsonify(errno=RET.NODATA, errmsg="商品不存在")

    # 将房屋对象数据转换为字典
    try:
        goods_data = goods.to_dict()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="数据出错")

    # 存入到redis中
    # houses_dict_del = dict(errno=RET.OK, errmsg="OK", data=house_data, current_user=user_id)
    # json_house = json.dumps(houses_dict_del)
    # try:
    #     redis_store.setex("house_info_%s" % house_id, constants.HOUSE_DETAIL_REDIS_EXPIRE_SECOND, json_house)
    # except Exception as e:
    #     current_app.logger.error(e)
    #
    # return json_house, 200, {"Content-Type": "application/json"}

    return jsonify(errno=RET.OK, errmsg="OK", data=goods_data)


@api.route("/goods/check_goods_exchange", methods=["POST"])
@login_required
def exchange_order():
    """兑换商品"""
    user_id = g.user_id

    # 获取参数
    order_data = request.get_json()
    goods_id = order_data.get("goods_id")
    address_id = order_data.get("address_id")

    if not order_data:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询商品是否存在和商品数量是否足够
    try:
        goods = IntegralGoods.query.filter_by(id=goods_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取商品信息失败")

    if not goods:
        return jsonify(errno=RET.NODATA, errmsg="商品不存在")
    if goods.count <= 0:
        return jsonify(errno=RET.NODATA, errmsg="商品数量不足")
        
    # 获取用户信息
    try:
        user = User.query.filter_by(id=user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="不存在用户信息")

    # 根据用户信息判断用户积分是否足够
    if user.integral < goods.need_integral:
        return jsonify(errno=RET.NODATA, errmsg="积分不足")

    # 保存更新完后的用户积分
    try:
        User.query.filter_by(id=user_id) \
            .update({"integral": user.integral-goods.need_integral})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="更新用户积分失败")

    # 更新兑换之后的商品数量和销售量
    try:
        goods = IntegralGoods.query.filter_by(id=goods_id).first()
        goods.count = goods.count-1
        goods.volume += 1
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="更新商品信息失败")

    # 保存订单数据
    goods_order = GoodsOrder(
        user_id=user_id,
        goods_id=goods_id,
        address_id=address_id,
        total_price=goods.need_integral
    )
    try:
        db.session.add(goods_order)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="兑换失败")
    return jsonify(errno=RET.OK, errmsg="兑换成功")
